package com.jike.shop.cloud.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Arrays;
import java.util.List;

/**
 * MyBatis配置类
 * Created by eagle on 2019/4/8.
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.jike.shop.cloud.mapper")
public class MyBatisConfig {
    /**
     * 分页
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        // 多租户解析器
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        // 设置多租户处理器
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId(boolean select) {
                return new StringValue("1");
            }

            @Override
            public String getTenantIdColumn() {
                // 对应数据库租户id的列名
                return "tenant_id";
            }

            @Override
            public boolean doTableFilter(String tableName) {
                // 过滤表
                List<String> tableNames = Arrays.asList("user", "order_info", "shopping_cart");
                return !tableNames.contains(tableName);
            }
        });
        return paginationInterceptor;
    }

    /**
     * 乐观锁
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
